<template>
  <px-dialog v-model="visible" title="自动组卷" width="1200" @close="cancel">
    <div class="question-info">
      <p class="score-info">当前分值{{ currentScore }}分/考试总分{{ totalScore }}分</p>
      <div class="flex-center">
        <div style="margin-right: 24px">单选题：{{ getSubjectInfo("S").num }}题共{{ getSubjectInfo("S").total }}分</div>
        <div style="margin-right: 24px">多选题：{{ getSubjectInfo("M").num }}题共{{ getSubjectInfo("M").total }}分</div>
        <div>判断题：{{ getSubjectInfo("T").num }}题共{{ getSubjectInfo("T").total }}分</div>
      </div>
    </div>
    <div class="content">
      <div v-loading="treeLoading" class="left-content">
        <div class="tree-title">
          <span>题目分类</span>
        </div>
        <div class="tree-search">
          <px-input v-model="treeSearchVal" placeholder="请输入" :prefix-icon="Search" clearable @change="getTreeData" />
        </div>
        <div class="tree-bar">
          <px-scrollbar>
            <px-tree
              ref="treeRef"
              :data="treeData"
              node-key="id"
              default-expand-all
              highlight-current
              :current-node-key="currentNode"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              @node-click="handleNodeClick"
            />
          </px-scrollbar>
        </div>
      </div>
      <div v-loading="loading" class="right-content">
        <px-form ref="formRef" :model="formParams" :rules="rules">
          <px-form-item label="组卷方式" prop="groupWay">
            <px-radio-group v-model="formParams.groupWay">
              <px-radio label="N">题目数量</px-radio>
              <px-radio label="S">题目分值</px-radio>
            </px-radio-group>
          </px-form-item>
          <px-form-item v-if="formParams.groupWay === 'N'" key="questionNum" label="添加数量" prop="questionNum">
            <px-input-number v-model="formParams.questionNum" style="width: 260px" placeholder="请输入添加数量" clearable />
            <!-- <span>该分类已有0题 共0分</span> -->
          </px-form-item>
          <px-form-item v-if="formParams.groupWay === 'S'" key="questionFenzhi" label="添加分值" prop="questionFenzhi">
            <px-input-number v-model="formParams.questionFenzhi" style="width: 260px" placeholder="请输入分值" clearable />
            <!-- <span>该分类已有0题 共0分</span> -->
          </px-form-item>
        </px-form>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <px-button @click="cancel">取消</px-button>
        <px-button type="primary" @click="save">确定</px-button>
      </span>
    </template>
  </px-dialog>
</template>
<script setup>
import { ref, reactive, toRefs, onMounted, nextTick, watch, computed } from "vue";
import { Search } from "@px-ui/icons-vue";
import { getQuestionCategoryListAPI, getQuestionFromAutoGroupAPI } from "@/api/knowledge/examManage";
import { PxMessage, PxMessageBox } from "px-ui";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  currentScore: {
    type: Number,
    default: 0
  },
  totalScore: {
    type: Number,
    default: 0
  },
  totalNum: {
    type: Number,
    default: 0
  },
  examId: {
    type: Number,
    default: null
  },
  getSubjectInfo: {
    type: Object,
    default: () => {}
  },
  questionIds: {
    type: Array,
    default: () => {}
  }
});

const emits = defineEmits(["update:visible", "save"]);

const visible = computed({
  get: () => props.visible,
  set: val => emits("update:visible", val)
});

const formRef = ref(null);
const treeRef = ref(null);

const state = reactive({
  treeLoading: false,
  treeData: [],
  treeSearchVal: "",
  currentNode: "0",
  formParams: {
    groupWay: "N",
    questionNum: null,
    questionFenzhi: null
  },
  loading: false
});
const { treeLoading, treeData, treeSearchVal, currentNode, formParams, loading } = toRefs(state);

const rules = computed(() => ({
  groupWay: [{ required: true, message: "请选择组卷方式", trigger: "change" }],
  questionNum: [{ required: true, message: "请输入添加数量", trigger: "blur" }],
  questionFenzhi: [{ required: true, message: "请输入分值", trigger: "blur" }]
}));

onMounted(() => {
  getTreeData();
});

watch(treeSearchVal, val => {
  treeRef.value.filter(val);
});

const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.includes(value);
};

const getTreeData = async () => {
  try {
    state.treeLoading = true;
    const params = {
      size: 9999,
      current: 1,
      name: state.treeSearchVal
    };
    const res = await getQuestionCategoryListAPI(params);
    state.treeData = res.records.map(item => {
      return {
        id: item.categoryId,
        label: item.category,
        children: []
      };
    });
    nextTick(() => {
      state.currentNode = res.records[0].id;
      treeRef.value.setCurrentKey(res.records[0].id);
      // handleQuery();
    });
  } catch (err) {
    console.log(err);
  } finally {
    state.treeLoading = false;
  }
};

// 点击树节点
const handleNodeClick = (data, node, obj) => {
  state.currentNode = data.id;
};

const getQuestion = async () => {
  try {
    state.loading = true;
    const params = {
      examId: props.examId,
      categoryId: state.currentNode,
      assembleWay: state.formParams.groupWay,
      assembleNumber: state.formParams.questionNum || state.formParams.questionFenzhi,
      questionIds: props?.questionIds || []
    };
    const res = await getQuestionFromAutoGroupAPI(params);
    res.forEach(item => {
      item.type = item.questionType;
      item.typeName = item.questionTypeName;
    });
    emits("save", res);
    emits("update:visible", false);
  } catch (error) {
    console.log(error);
  } finally {
    state.loading = false;
  }
};

const cancel = () => {
  emits("update:visible", false);
};
const save = () => {
  formRef.value?.validate(async validate => {
    if (validate) {
      getQuestion();
    }
  });
};
</script>
<style lang="scss" scoped>
@import url("@/views/all/knowledge/examManage/scss/common.scss");

.question-info {
  margin-bottom: 16px;
  font-size: 14px;
  color: rgb(0 0 0 / 85%);
}

.score-info {
  margin-bottom: 8px;
}

.content {
  display: flex;
}

.left-content {
  width: 316px;
  height: 500px;
  border: 1px solid #dfdfdf;
  border-radius: 4px;

  .tree-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 8px 8px 0;
    font-size: 14px;
    font-weight: bold;
    color: rgb(0 0 0 / 80%);
  }

  .tree-search {
    padding: 8px;
  }

  .tree-bar {
    width: 100%;
    height: 418px;
    overflow-y: auto;
  }
}

.right-content {
  width: calc(100% - 316px);
  height: 100%;
  padding-left: 18px;
}
</style>
